<!-- @format -->

<!--海外出库-复核打包-->

<template>
	<div class="page-container" style="min-height: 55rem;">
		<!-- <page_breadcrumb :getKeyMethod="init_table_model" @change="change_table_model" modelPath="tableOption.model" /> -->
		<audio ref="error_audio">
			<source src="../../../../asset/error_audio.wav" type="audio/mpeg" />
			Your browser does not support the audio element.
		</audio>
		<el-form label-position="right" ref="formSearch" onsubmit="return false" :rules="rules" :model="{}">
			<div class="flex_row">
				<el-checkbox class="mg_1" :value="autoPrint" border @change="changeAutoPrint">
					{{ $tt('label_auto_print') }}
				</el-checkbox>

				<el-checkbox class="mg_1" v-model="autoMeasure" border @input="configChange"> {{ $t('label_auto_measure') }}</el-checkbox>
				<el-checkbox class="mg_1" v-model="packageExamine" border @input="configChange"> {{ $t('label_package_examine') }}</el-checkbox>
				<el-checkbox class="mg_1" v-model="autoPushOver" border @input="configChange"> {{ $t('label_auto_confirm_package') }}</el-checkbox>
				<auto_weight_input v-model="autoWeightValue" class="mg_h2 form_input_default" @stableValue="autoWeightConnectValue" />
			</div>
			<div class="flex_row_wrap mg_t2">
				<div class="mg_h1">
					<ex_select_auto v-model="orderStructures" :placeholder="$t('label_order_filter')" enum="OutboundOrderStructureEnum" clearable multiple />
				</div>

				<el-form-item class=" " prop="searchCode">
					<el-dropdown
						trigger="click"
						@command="
							(e) => {
								searchType = e;
								configChange();
							}
						"
					>
						<span class="el-dropdown-link"> {{ $tt(searchTypeList[searchType].label) }}<i class="el-icon-arrow-down el-icon--right"></i> </span>
						<el-dropdown-menu slot="dropdown">
							<el-dropdown-item :command="item.value" :key="item.value" v-for="item of searchTypeList">{{ $t(item.label) }}</el-dropdown-item>
						</el-dropdown-menu>
					</el-dropdown>
					<scan_input v-model.trim="searchCode" @enterInput="scanSkuCode" style="width:400px" class="form_input_default mg_l1" autofocus> </scan_input>
					<el-button class="mg_l1" @click="scanSkuCode" type="primary" style="width:110px"> {{ $tt('label_scan') }}</el-button>
					<el-button @click="refreshTrackNet">{{ $t('label_refresh_face_order') }}</el-button>
				</el-form-item>
			</div>
		</el-form>

		<el-row :gutter="20">
			<el-col :lg="12" :md="24" style="height:260px;margin-bottom: 10px;">
				<div class=" flex_col card_1" key="skuLinkTableDiv" style="height: 100%; box-sizing: border-box;">
					<template v-if="linkSearchCode">
						<div class="mg_v2 flex_row_center">
							{{ $tt('tip_xxx_link_track_info', { code: linkSearchCode }) }}
						</div>
						<ex_super_table :data="trackList" v-bind="trackTableOption" border autoFlex key="skuLinkTable"> </ex_super_table>
					</template>
					<template v-else>
						<div class="flex_auto flex_center  mg_1 ">
							<div class="color_info">{{ $tt('tip_scan_sku_only_code_first') }}</div>
						</div>
					</template>
				</div>
			</el-col>
			<el-col :lg="12" :md="24" style="height: 260px;margin-bottom: 10px;">
				<div class=" flex_col card_1" key="trackLinkTableDiv" style="height: 100%; box-sizing: border-box;">
					<transition name="el-zoom-in-top" mode="out-in" :duration="200">
						<div v-if="!!trackItem" class=" flex_col flex_cell">
							<div class="mg_v2">
								{{ $tt('tip_linkTrackNumber_now_track_check_pack_info', { linkTrackNumber: trackItem.trackNumber }) }}
							</div>
							<ex_super_table :data="trackItem.waitPackSkuVOList" v-bind="trackSkuTableOption" border autoFlex key="trackLinkTable" :row-class-name="packTableRowClass"> </ex_super_table>
						</div>
						<div v-else class=" flex_center flex_cell">
							{{ $tt('label_wait_pack_area') }}
						</div>
					</transition>
					<div v-if="this.trackItem && !this.trackItem.push_over">
						<el-button @click="cancelTrackConfirm">
							{{ $tt('label_cancel') }}
						</el-button>
						<el-button type="warning" @click="reportAnomaly">
							{{ $tt('label_report_exception') }}
						</el-button>
						<el-button type="warning" v-if="this.trackItem && this.trackItem.isShortPick && this.trackItem.ullageFlag == 'Y'" @click="pushCurrentTrackDown">
							{{ $t('label_retry_check_short_pick') }}
						</el-button>
						<el-button type="primary" v-if="this.trackItem.finish == true" @click="pushCurrentTrackDown">
							{{ $t('label_confirm_package') }}
						</el-button>
					</div>
				</div>
			</el-col>
		</el-row>
		<div class="flex_row flex_justify_sb mg_v2">
			<div></div>
			<div class="flex_row">
				<el-button @click="save_pack_data">{{ $tt('label_temp_save_pack_data') }}</el-button>
				<el-button v-if="hasTempData" @click="restore_pack_data">{{ $tt('label_restore_pack_data') }}</el-button>
				<el-button v-if="trackSwitchList.length" type="warning" @click="$refs.print_outbound_switch_track.show(trackSwitchList)">
					{{ $tt('label_now_retry_get_face_track_list') }}({{ trackSwitchList.length }})</el-button
				>
				<el-button type="primary" @click="reviewConfirm">{{ $tt('label_audit_confirm') }}</el-button>
				<el-button @click="goToRecord">{{ $tt('label_check_pack_record') }}</el-button>
			</div>
		</div>

		<ex_super_table class="flex_auto" style="min-height: 350px;" v-bind="tableOption" :data="tableData" :autoFlex="true" :autoPage="false" :specialStyle="false" :span-method="objectSpanMethod">
		</ex_super_table>
		<ex_super_dialog_form ref="measureFormDialog" :title="$tt('label_check_pack_measure')" v-bind="measureDialog" @afterSubmitSuccess="measureSubmit"> </ex_super_dialog_form>
		<print_outbound_track
			ref="print_outbound_track"
			:tableModel="[
				{ key: 'trackNumber', label: 'label_track_or_package_code', 'min-width': 120, 'show-overflow-tooltip': true },
				{ key: 'skuKindLength', label: 'label_sku_kind', width: 120, 'show-overflow-tooltip': true },
				{ key: 'skuSum', label: 'label_sku_count_sum', width: 120, 'show-overflow-tooltip': true },
			]"
		/>

		<print_outbound_switch_track ref="print_outbound_switch_track" />

		<report_anomaly ref="report_anomaly" system="WMS" :orderTypeList="['OUTBOUND']" :extraModel="[{ key: 'trackNumber', label: 'label_face_track_code', formType: 'text' }]" />

		<print_config_dialog ref="print_config_dialog" printType="OUTBOUND_WAYBILL" @saveConfig="saveConfig" />
	</div>
</template>
<script>
import print_config_dialog from '@/component/print/common_print_config_dialog.vue';

import tag_before_unload from '@/mixin/tag_before_unload';
import superTablePageFunction from '@/mixin/super-table-page-function';
import print_outbound_track from '@/component/print/print_outbound_track';
import print_outbound_switch_track from '@/component/print/print_outbound_switch_track';

import report_anomaly from '@/component/dialog/report_anomaly.vue';
import auto_weight_input from '@/component/serial_port/auto_weight_input.vue';

import page_table_model_manage from '@/mixin/page_table_model_manage';
import pack_material_cascader from '@/component/wms/pack_material_cascader.vue';

import popover_sn_detail from '@/component/wms/popover_sn_detail';

export default {
	title: 'title_standard_check_pack',
	mixins: [superTablePageFunction, page_table_model_manage, tag_before_unload],
	components: {
		auto_weight_input,
		pack_material_cascader,
		print_outbound_track,
		print_outbound_switch_track,
		report_anomaly,
		popover_sn_detail,
		print_config_dialog,
	},
	data() {
		return {
			searchTypeList: {
				SKU: { label: 'label_sku_only_code', value: 'SKU', netKey: 'skuOnlyCode', searchKey: 'skuOnlyCode', scanInto: true },
				PICKCAR: { label: 'label_pick_car_code', value: 'PICKCAR', netKey: 'pickCarCode', searchKey: 'skuOnlyCode' },
				CONTAINER: { label: 'label_sort_pick_container_code', value: 'CONTAINER', netKey: 'pickContainerNo', searchKey: 'skuOnlyCode', onlyOneTrack: true },
				BOX: { label: 'label_box_code', value: 'BOX', netKey: 'boxNo', searchKey: 'boxNo', scanInto: true },
				FACE: { label: 'label_face_track_code', value: 'FACE', netKey: 'trackNumber', searchKey: 'skuOnlyCode', onlyOneTrack: true },
			},
			searchType: 'SKU',
			searchCode: '',

			autoMeasure: true,

			autoPushOver: false,
			autoWeightValue: '',
			autoWeightValueStable: '',

			//订单筛选
			orderStructures: [],
			//打包复核
			packageExamine: false,
			hasTempData: false,
			rules: {
				searchCode: {
					required: true,
					trigger: 'blur',
					validator: (r, v, cb) => {
						if (_.isEmpty(this.searchCode)) {
							return cb(this.$tt('tip_can_no_empty'));
						}
						cb();
					},
				},
			},
			autoPrint: false,
			linkSearchCode: '',
			skuNumber: 0,

			packId: null,
			packCode: null,
			packName: null,
			packTypeName: null,
			packTypeId: null,

			trackList: [],
			trackSwitchList: [],
			trackItem: null,
			tableData: [],
			tableOption: {
				model: this.init_table_model(),
			},
			tableDataStorageKey:'outbound>check_pack>tableData?w='+this.$loginUser.currentWarehouseId+"$u="+this.$loginUser.userId,
			trackTableOption: {
				model: [
					{
						key: 'trackNumber',
						label: 'label_track_or_package_code',
						'min-width': 160,
						'show-overflow-tooltip': true,
						render: (h, { row }) => {
							return (
								<div class='bold'>
									<span>{row.trackNumber}</span>
									<el-button class='mg_l2' size='mini' type='text' onClick={() => this.copyToClip(row.trackNumber)}>
										{this.$tt('label_copy')}
									</el-button>
								</div>
							);
						},
					},
					{ key: 'bizType', label: 'label_business_type', width: 120, formatter: (r, c, v) => this.$enumShow(v, 'BizTypeEnum') },

					{
						key: 'finish',
						label: 'label_check_pack_info',
						width: 120,
						render: (h, { row }) => {
							if (row.interceptFlag == 'Y') {
								return (
									<div class='flex_center bold'>
										<i class={'el-icon-error color_danger el-icon--left'}></i>
										<span class={'color_danger'}>{this.$tt('label_order_intercept')}</span>
									</div>
								);
							}
							return (
								<div class='flex_center bold'>
									<i
										class={
											row.push_over
												? 'el-icon-success color_success el-icon--left'
												: this.trackItem && this.trackItem.trackNumber == row.trackNumber
												? 'color_primary el-icon-s-flag el-icon--left'
												: row.isShortPick == true
												? 'el-icon-warning color_warning el-icon--left'
												: 'el-icon-error el-icon--left'
										}
									></i>
									<span class={row.push_over ? 'color_success' : this.trackItem && this.trackItem.trackNumber == row.trackNumber ? 'color_primary' : row.isShortPick == true ? 'color_warning' : ''}>
										{row.push_over
											? this.$tt('label_has_finish')
											: this.trackItem && this.trackItem.trackNumber == row.trackNumber
											? this.$tt('label_operate_ing')
											: row.isShortPick == true
											? this.$tt('label_short_pick')
											: this.$tt('label_no_finish')}
									</span>
								</div>
							);
						},
					},
					{ key: 'channelName', label: 'label_pms_supply', width: 100, 'show-overflow-tooltip': true },

					{ key: 'skuKindLength', label: 'label_sku_kind', width: 100, 'show-overflow-tooltip': true },
					{ key: 'skuSum', label: 'label_sku_count_sum', width: 100, 'show-overflow-tooltip': true },
					// {
					//   key: 'trackOwner', label: 'label_track_owner', 'width': 100, 'show-overflow-tooltip': true,
					//   formatter: (r, c, v, i) => this.$enumShow(v, 'LineOwnerEnum'),
					// },

					{
						type: 'operate',
						width: 120,
						operate: [
							{
								label: 'label_select',
								if: (row) => !this.trackSwitchList.some((it) => it.trackNumber === row.trackNumber),
								click: (row) => {
									if (this.trackItem && this.trackItem.trackNumber == row.trackNumber) return;
									this.scanTrackNumber(row.trackNumber);
								},
							},
							{
								label: 'label_abnormal',
								if: (row) => this.trackSwitchList.some((it) => it.trackNumber === row.trackNumber),
								class: 'button_text_warning',
								click: (row) => {
									this.$message.warning(this.$t('label_weight_over_deviation_face_track_need_update'));
								},
							},
						],
					},
				],
			},
			trackSkuTableOption: {
				model: [
					{ key: 'boxNo', label: 'label_box_code', 'min-width': 130, if: () => this.trackIsBox },
					{ key: 'skuOnlyCode', label: 'label_sku_code', 'min-width': 130 },
					{
						key: 'skuNameCn',
						label: 'label_sku_name',
						'min-width': 140,
						formatter: (r, c, v, i) => this.$formatNameCode(v, r.skuNameEn),
					},
					{
						key: 'actualNum',
						label: 'label_pick_count',
						width: 100,
						render: (h, { row }) => {
							return <div class='bold'>{row.actualNum}</div>;
						},
					},
					{
						key: 'scanNumber',
						label: 'label_check_pack_count',
						width: 100,
						render: (h, scope) => {
							return h(popover_sn_detail, {
								props: {
									textClass: 'bold',
									value: scope.row.scanNumber,
									list: scope.row.skuOutboundDetailList,
								},
							});
						},
					},

					{
						key: 'finish',
						label: 'label_check_pack_is_finish',
						width: 120,
						render: (h, { row }) => {
							return (
								<div class='flex_center bold'>
									<i class={row.isShortPick == true ? 'el-icon-warning color_warning el-icon--left' : row.finish ? 'el-icon-success color_success el-icon--left' : 'el-icon-error el-icon--left'}></i>
									<span class={row.isShortPick == true ? 'color_warning' : row.finish ? 'color_success' : ''}>
										{row.isShortPick == true ? this.$tt('label_short_pick') : row.finish ? this.$tt('label_has_finish') : this.$tt('label_no_finish')}
									</span>
								</div>
							);
						},
					},
				],
			},
			measureDialog: {
				customClass: 'dialog_auto',
				form: {
					itemClass: 'form_item_default',
					inputClass: 'form_input_default',
					model: [
						{ key: 'packageNo', label: 'label_track_or_package_code', formType: 'text' },
						{ key: 'bizType', label: 'label_business_type', formType: 'text', formatter: (r, c, v) => this.$enumShow(v, 'BizTypeEnum') },

						{
							key: 'packageWeight',
							label: 'label_check_pack_weight', // append: 'kg', appendClass: 'input_slot_div_mini',
							render: (h, { data }) => {
								return h(auto_weight_input, {
									key: 'auto_weight_input=' + data.packageNo,
									class: 'form_input_default',
									props: {
										value: data.packageWeight,
									},
									on: {
										input: (e) => this.$set(data, 'packageWeight', e),
									},
								});
							},
						},
						{ key: 'length', label: 'label_check_pack_length', append: 'cm', appendClass: 'input_slot_div_mini' },
						{ key: 'width', label: 'label_check_pack_width', append: 'cm', appendClass: 'input_slot_div_mini' },
						{ key: 'height', label: 'label_check_pack_height', append: 'cm', appendClass: 'input_slot_div_mini' },
						{
							label: 'label_table_operate_area',
							if: (data) => data.some_package,
							render: (h, { data }) => {
								return h(
									'el-button',
									{
										on: {
											click: (e) => this.autoMeasureForSku(data),
										},
									},
									this.$tt('label_sku_auto_measure')
								);
							},
						},
					],
					rules: {
						// 'vehicleTypeName': { required: true, message: '不能为空', trigger: 'blur' },
						packageNo: {
							required: true,
							trigger: 'blur',
							validator: (r, v, cb) => {
								if (_.isEmpty(v)) return cb(this.$tt('tip_can_no_empty'));
								if (this.tableData.every((it) => it.packageNo != v)) {
									return cb(this.$tt('tip_please_check_pack_finish_first'));
								}
								cb();
							},
						},
						packageWeight: {
							required: true,
							trigger: 'blur',
							validator: (r, v, cb) => {
								if (!v) {
									cb(this.$tt('tip_can_no_empty'));
								} else if (Number.isNaN(Number(v))) {
									cb(this.$t('tip_format_error'));
								} else {
									cb();
								}
							},
						},
						length: {
							required: true,
							trigger: 'blur',
							validator: (r, v, cb) => {
								if (this.$ruleStandard({ v, cb, type: 'dimen', required: true })) cb();
							},
						},
						width: {
							required: true,
							trigger: 'blur',
							validator: (r, v, cb) => {
								if (this.$ruleStandard({ v, cb, type: 'dimen', required: true })) cb();
							},
						},
						height: {
							required: true,
							trigger: 'blur',
							validator: (r, v, cb) => {
								if (this.$ruleStandard({ v, cb, type: 'dimen', required: true })) cb();
							},
						},
					},
				},
			},
		};
	},

	mounted() {
		let packConfig = window.localStorage.getItem('outbound>check_pack>packConfig');
		if (packConfig) {
			try {
				packConfig = JSON.parse(packConfig);
				this.autoMeasure = !!packConfig.autoMeasure;
				this.autoPushOver = !!packConfig.autoPushOver;
				this.packageExamine = !!packConfig.packageExamine;
				this.autoPrint = !!packConfig.autoPrint;
				this.searchType = (packConfig && packConfig.searchType) || 'SKU';
				this.orderStructures = packConfig.orderStructures ? packConfig.orderStructures.split(',').filter((it) => it) : [];
			} catch (e) {}
		}

		if (this.autoPrint) {
			const printConfig = _.head(this.$refs.print_config_dialog.loadPrintConfig({ typeKey: 'OUTBOUND_WAYBILL' }));
			if (!printConfig || !printConfig.clientId || !printConfig.templateId) {
				this.autoPrint = false;
			}
		}
		this.hasTempData = !!window.localStorage.getItem(this.tableDataStorageKey);
	},
	computed: {
		trackIsBox() {
			return this.trackItem.waitPackSkuVOList.some((it) => !!it.boxNo);
		},
		flowIsNeedSwitchFace() {
			return (
				this.$store.state.autoConfig['com.iml.wms.config.auto_config.WmsOutboundAutoConfig->pkgWeighAssign'] == 'true' &&
				this.$store.state.autoConfig['com.iml.wms.config.auto_config.WmsOutboundAutoConfig->pkgWeighAssignRule'] == 'UPDATE_WAYBILL'
			);
		},
	},

	watch: {
		tableData: function(newVal, oldVal) {
			if (_.isEmpty(newVal)) {
				this.remove_tag_beforeunload();
			} else {
				this.add_tag_beforeunload();
			}
			
		},
	},
	beforeDestroy() {
		this.remove_tag_beforeunload();
	},
	methods: {
		autoWeightConnectValue(v) {
			if (this.$clickFast()) return;
			if (this.trackItem && this.trackItem.finish && !this.trackItem.push_over) {
				this.pushCurrentTrackDown();
			}
		},

		configChange() {
			const data = {
				autoMeasure: this.autoMeasure,
				autoPushOver: this.autoPushOver,
				packageExamine: this.packageExamine,
				searchType: this.searchType,
				autoPrint: this.autoPrint,
				orderStructures: this.orderStructures.join(',') || '',
			};
			window.localStorage.setItem('outbound>check_pack>packConfig', JSON.stringify(data));
		},
		save_pack_data() {
			if (_.isEmpty(this.tableData)) {
				this.$alert(this.$t('tip_no_has_pack_data_place_pack'), this.$tt('label_tip'), {
					callback: (action) => {},
				});
				return;
			}
			const run = () => {
				window.localStorage.setItem(this.tableDataStorageKey, JSON.stringify(this.tableData));
				this.tableData = [];
				this.hasTempData = true;
			};
			let data = window.localStorage.getItem(this.tableDataStorageKey);
			if (data) {
				this.$confirm(this.$tt('tip_has_temp_save_pack_data_is_over'), this.$tt('label_tip'), {
					type: 'warning',
				})
					.then(() => {
						run();
					})
					.catch(() => {});
			} else {
				run();
			}
		},
		restore_pack_data() {
			const run = () => {
				let data = window.localStorage.getItem(this.tableDataStorageKey);
				if (data) {
					try {
						data = JSON.parse(data);
						if (_.isArray(data)) {
							this.tableData = data;
							window.localStorage.removeItem(this.tableDataStorageKey);
							this.hasTempData = false;
						} else {
							this.$message.warning(this.$t('tip_no_has_temp_save_data_is_over'));
						}
					} catch (e) {}
				} else {
					this.$message.warning(this.$t('tip_no_has_temp_save_data_is_over'));
				}
			};
			if (!_.isEmpty(this.tableData)) {
				this.$confirm(this.$tt('tip_has_pack_data_is_over'), this.$tt('label_tip'), {
					type: 'warning',
				})
					.then(() => {
						run();
					})
					.catch(() => {});
			} else {
				run();
			}
		},
		option_table_model() {
			return [
				{ key: 'packageBoxNo', label: 'label_box_code', 'min-width': 140 },

				{ key: 'packageNo', label: 'label_track_or_package_code', 'min-width': 140 },
				{ key: 'bizType', label: 'label_business_type', width: 120, formatter: (r, c, v) => this.$enumShow(v, 'BizTypeEnum') },

				{ key: 'skuOnlyCode', label: 'label_sku_only_code', 'min-width': 120 },
				{ key: 'skuName', label: 'label_sku_name', width: 120, 'show-overflow-tooltip': true },
				{
					key: 'customerName',
					label: 'label_customer_name',
					width: 140,
					'show-overflow-tooltip': true,
					formatter: (r, c, v, i) => this.$formatNameCode(v, r.customerCode),
				},
				{ key: 'number', label: 'label_sku_count', width: 80 },
				// { key: 'actualNum', label: 'label_actual_count', 'width': 80, },
				{
					key: 'scanNumber',
					label: 'label_scan_count',
					width: 90,
					render: (h, scope) => {
						return h(popover_sn_detail, {
							props: {
								textClass: 'bold',
								value: scope.row.scanNumber,
								list: scope.row.skuOutboundDetailList,
							},
						});
					},
				},
				{
					key: 'packUnit',
					label: 'label_pack_unit',
					width: 150,
					render: (h, { column, row, index }) => {
						const value = row[column.property];
						return (
							<ex_select_auto
								value={value}
								enum='PackUnitEnum'
								class='w_fill'
								onInput={(value) => {
									this.$set(row, column.property, value);
								}}
								placeholder={column.label}
							></ex_select_auto>
						);
					},
				},
				{
					key: 'packCount',
					label: 'label_pack_count',
					width: 150,
					render: (h, { column, row, index }) => {
						const value = row[column.property];
						return (
							<el-input-number
								value={value}
								class='w_fill'
								min={0}
								max={10}
								onInput={(value) => {
									this.$set(row, column.property, value);
								}}
								placeholder={column.label}
							></el-input-number>
						);
					},
				},
				{
					key: 'channelName',
					label: 'label_pms_supply',
					width: 100,
					'show-overflow-tooltip': true,
				},
				{
					key: 'packageWeight',
					label: 'label_check_pack_weight',
					width: 100,
					formatter: (r, c, v, i) => this.$addUnit(this.$formatDigit(v, 3), 'kg'),
				},
				// { key: 'packageVolume', label: 'label_check_pack_volume', 'width': 80, },
				{
					key: 'size',
					label: 'label_check_pack_size',
					width: 130,
					formatter: (r, c, v, i) => this.$addUnit([this.$formatDigit(r.length, 2), this.$formatDigit(r.width, 2), this.$formatDigit(r.height, 2)].join('*'), 'cm'),
				},
				{
					key: 'heavyCargoFlag',
					label: 'label_is_heavy_good',
					width: 100,
					formatter: (r, c, v, i) => this.$enumShow(r.packageWeight > 25 ? 'Y' : 'N', 'YesOrNoEnum'),
				},
				// savePackageList.forEach(it => {
				//   it.heavyCargoFlag = it.packageWeight > 25 ? "Y" : "N"
				// })
				// { key: 'length', label: 'label_check_pack_length', 'width': 80, },
				// { key: 'width', label: 'label_check_pack_width', 'width': 80, },
				// { key: 'height', label: 'label_check_pack_height', 'width': 80, },
				// { key: 'packageType', label: 'label_pack_material_type', 'width': 100, 'show-overflow-tooltip': true, },
				// { key: 'packageName', label: 'label_pack_material_name', 'width': 100, 'show-overflow-tooltip': true, },
				{
					type: 'operate',
					key: 'operate',
					fixed: 'right',
					width: 190,
					operate: [
						{
							label: 'label_self_draw_face_track',
							if: (row) => this.checkSelfTempPrint(row),
							click: (row) =>
								this.$refs.print_outbound_track.show([row], {
									extraBusinessType: this.checkThreeTrackPrint(row) ? row.platformCode : null,
									thirdParty: false,
									single: true,
								}),
						},
						{
							label: 'label_third_party_face_track',
							if: (row) => this.checkThreeTrackPrint(row),
							click: (row) =>
								this.$refs.print_outbound_track.show([row], {
									extraBusinessType: row.platformCode,
									thirdParty: true,
									single: true,
								}),
						},
						{
							label: 'label_check_pack_measure',
							click: (row) => this.measureFunction(row),
						},
						// {
						//   label: 'label_modify_count',
						//   if: row => row.isShortPick == true,
						//   click: (row) => this.modifyRecord(row),
						// },
						{
							label: 'label_cancel',
							type: 'confirm-button',
							message: 'text_confirm_sure_cancel',
							buttonClass: 'button_text_danger',
							confirmButtonType: 'danger',
							done: (row, i) => this.cancelHasAddTrack(row, i),
						},
					],
				},
			];
		},
		reportAnomaly() {
			if (this.trackItem.oldWaybillFlag == 'Y') {
				this.$message.error(this.$t('label_face_track_has_be_update'));
				return;
			}
			this['$refs']['report_anomaly'].showNew({
				formDisabled: true,
				detailUrl: '/wms-api/outbound/OutboundBoxPackageRpc/getOrderInfo.json',
				params: { trackNumber: this.trackItem.trackNumber },
				detailDataHandle: (data) => {
					return {
						customerId: data.customerId,
						customerCode: data.customerCode,
						customerName: data.customerName,
						orderType: 'OUTBOUND',
						orderNo: data.outOrderNo,
						trackNumber: this.trackItem.trackNumber,
					};
				},
			});
		},
		changeAutoPrint(e) {
			if (!this.autoPrint) {
				const printConfig = _.head(this.$refs.print_config_dialog.loadPrintConfig({ typeKey: 'OUTBOUND_WAYBILL' }));
				if (!printConfig || !printConfig.clientId || !printConfig.templateId) {
					this.autoPrint = false;
					this.$refs.print_config_dialog.show();
					return;
				} else {
					this.autoPrint = true;
				}
			} else {
				this.autoPrint = false;
			}
			this.configChange();
		},
		saveConfig() {
			const printConfig = _.head(this.$refs.print_config_dialog.loadPrintConfig({ typeKey: 'OUTBOUND_WAYBILL' }));
			if (!printConfig || !printConfig.clientId || !printConfig.templateId) {
			} else {
				this.autoPrint = true;
				this.configChange();
			}
		},

		goToRecord() {
			this.$router.push({ path: '/page/wms/overseas/outbound/check_pack_record', query: { userName: this.$loginUser.userName } });
		},
		searchTypeChange() {
			this.trackList = [];
			this.trackItem = null;
			this.searchCode = '';
			this.linkSearchCode = '';
		},
		measureFunction(row) {
			if (row) {
				const data = _.cloneDeep(row);
				const some_package = this.tableData.filter((it) => it.packageNo == row.packageNo);
				data.some_package = some_package;
				data.row = row;
				this['$refs']['measureFormDialog'].show(data, true);
			}
		},
		//面单检查更换
		checkSwitchFaceTrack({ newWeight, switchFaceTrackList, success, failure }) {
			const item = _.head(switchFaceTrackList);
			let needSwtich = this.flowIsNeedSwitchFace && item.trackOwner !== 'SELF_SUPPORT' && item.oldWaybillFlag !== 'Y';
			if (needSwtich) {
				needSwtich = item.plan && Number(item.plan.packageWeight) < Number(newWeight) && !Number.isNaN(Number(item.deviationRate));
				if (needSwtich) {
					const rate = this.$math_round(this.$math_mul(this.$math_div(this.$math_sub(Number(newWeight), Number(item.plan.packageWeight)), Number(item.plan.packageWeight)), 100), 0);
					needSwtich = rate > Number(item.deviationRate);
				}
			}
			if (needSwtich) {
				this.$ajax({
					url: '/wms-api/outbound/OutboundBoxPackageRpc/updateWaybill.json',
					method: 'post',
					loading: this.$t('label_search_face_track_ing'),
					data: {
						outOrderNo: item.outOrderNo,
						trackNumber: item.trackNumber,
						customerId: item.customerId,
						// weight: item.plan.packageWeight,
						// newWeight: newWeight,
					},
					success: (res) => {
						if (res && res.data && res.data.mainTrackNumber !== item.trackNumber) {
							this.$message.warning(this.$t('label_weight_over_deviation_face_track_need_update'));
							switchFaceTrackList.forEach((it) => (it.switchFace = true));
							if (success) success(switchFaceTrackList, true);
						} else {
							if (success) success(switchFaceTrackList, false);
						}

						// let switchFace = false
						// //面单已被更新
						// if (res.data && res.data.oldWaybillFlag == 'Y') {
						//   this.trackList.forEach(it => {
						//     if (it.trackNumber == item.trackNumber) {
						//       this.$set(it, 'oldWaybillFlag', 'Y')
						//     }
						//   })
						//   if (this.trackItem && this.trackItem.trackNumber == item.trackNumber) {
						//     this.$set(this.trackItem, 'oldWaybillFlag', 'Y')
						//   }
						//   switchFaceTrackList.forEach(it => {
						//     this.$set(it, 'oldWaybillFlag', 'Y')
						//   })
						//   this.$message.error(this.$t('label_face_track_has_be_update'))
						//   if (failure) failure(switchFaceTrackList)
						//   return
						// }
						// if (res.data && res.data.trackNumber) {
						//   this.$nextTick(() => {
						//     this.$message.success(this.$t('label_retry_get_face_track_success'))
						//     const tip_new_face = this.$t('label_new_face_track_code')
						//     const tip_get_face_track_success = this.$t('label_retry_get_face_track_success')
						//     this.$notify({
						//       title: this.$t('label_face_track_info'),
						//       dangerouslyUseHTMLString: true,
						//       message: `<div>
						//     <div>${tip_get_face_track_success}</div>
						//     <div>${tip_new_face}：<strong>${res.data.trackNumber}</strong></div>
						//     </div>`,
						//       type: 'warning'
						//     });
						//   })
						//   this.trackList.forEach(it => {
						//     if (it.trackNumber == item.trackNumber) {
						//       this.$set(it, 'trackNumber', res.data.trackNumber)
						//       this.$set(it, 'labelOssPath', res.data.labelOssPath)
						//     }
						//   })
						//   if (this.trackItem && this.trackItem.trackNumber == item.trackNumber) {
						//     this.$set(this.trackItem, 'trackNumber', res.data.trackNumber)
						//     this.$set(this.trackItem, 'labelOssPath', res.data.labelOssPath)
						//   }
						//   switchFaceTrackList.forEach(it => {
						//     this.$set(it, 'trackNumber', res.data.trackNumber)
						//     this.$set(it, 'packageNo', res.data.trackNumber)
						//     this.$set(it, 'labelOssPath', res.data.labelOssPath)
						//   })
						//   switchFace = true
						// }
					},
					failure: () => {
						if (failure) failure(switchFaceTrackList);
					},
					complete: () => {},
				});
			} else {
				if (success) success(switchFaceTrackList);
			}
		},
		measureSubmit(data) {
			this.checkSwitchFaceTrack({
				newWeight: data.packageWeight,
				// item: data.row,
				switchFaceTrackList: this.tableData.filter((it) => it.trackNumber == data.trackNumber),
				success: (list, switchFace) => {
					list.forEach((it) => {
						this.$set(it, 'packageWeight', data.packageWeight);
						this.$set(it, 'length', data.length);
						this.$set(it, 'width', data.width);
						this.$set(it, 'height', data.height);
					});

					if (switchFace) {
						this.tableData = this.tableData.filter((it) => it.trackNumber != data.trackNumber);
						this.trackSwitchList.push(list[0]);
					}
					if (this.autoPrint && switchFace) {
						this.autoPrintAction([list[0]]);
					}
				},
			});
		},
		autoMeasureForSku(formData) {
			if (!formData.some_package) return this.$message.error('无法自动测量');
			this.autoMeasureForSkuNet({
				items: formData.some_package,
				success: (res) => {
					this.$set(formData, 'packageWeight', res.weight);
					this.$set(formData, 'length', res.length);
					this.$set(formData, 'width', res.width);
					this.$set(formData, 'height', res.height);
				},
			});
		},
		autoMeasureForSkuNet({ items, success, fail }) {
			const box = _.find(items, (it) => it.packageBoxNo);
			const data = {};
			if (box) {
				data.boxNo = box.packageBoxNo;
			} else {
				data.packageSkuInfoList = items.map((it) => ({
					skuId: it.skuId,
					count: it.scanNumber,
				}));
			}
			this.$ajax({
				url: '/wms-api/outbound/OutboundBoxRpc/getPackageAttrResult.json',
				method: 'post',
				type: 'json',
				loading: true,
				data,
				success: (res) => {
					if (res.data) {
						const weight = res.data.weight;
						// this.$set(formData, 'packageWeight', res.data.weight)
						const size_list = [Number(res.data.length), Number(res.data.width), Number(res.data.height)];
						size_list.sort((a, b) => b - a);
						const length = size_list[0];
						const width = size_list[1];
						const height = size_list[2];
						// this.$set(formData, 'length', size_list[0])
						// this.$set(formData, 'width', size_list[1])
						// this.$set(formData, 'height', size_list[2])
						if (success) success({ weight, length, width, height });
					} else {
						if (fail) fail();
					}
				},
				failure: () => {
					if (fail) fail();
				},
				complete: () => {},
			});
		},
		objectSpanMethod({ row, column, rowIndex, columnIndex }) {
			let _list = ['packageNo', 'packageType', 'packageName', 'packageVolume', 'size', 'packageWeight'];
			if (_list.includes(column.property) || column.type == 'operate') {
				return { rowspan: row.rowspan, colspan: 1 };
			}
		},

		copyToClip(text) {
			this.$copyToClip(text, this.$tt('label_has_copy'));
		},
		packTableRowClass({ row, rowIndex }) {
			if (row.finish == true) {
				return 'back_success_light2 back_success_light2_hover';
			}
			return '';
		},
		//添加sku记录
		checkSkuPackPush({ code, track, finishBeforeCall, finishCall, tipShow, snSku }) {
			if (!code) code = this.linkSearchCode;
			if (!track) {
				this.$refs.error_audio.play();
				return this.$message.error(this.$tt('label_get_track_info_fail'));
			}
			const toBox = track.waitPackSkuVOList.some((it) => it.boxNo);

			if (!code) {
				this.$refs.error_audio.play();
				return this.$message.error(this.$tt('tip_scan_sku_code_first'));
			}
			if (this.trackSwitchList.some((it) => it.trackNumber === track.trackNumber)) {
				this.$refs.error_audio.play();
				return this.$message.error(this.$tt('label_face_track_has_be_update'));
			}
			const config = this.searchTypeList[this.searchType];

			// let skuItem = _.find(track.waitPackSkuVOList, it => it.skuOnlyCode == code|| it.boxNo == code)
			if (toBox) {
				let boxItem = _.find(track.waitPackSkuVOList, (it) => it.boxNo == code);
				if (!boxItem) {
					this.$refs.error_audio.play();
					return this.$message.error(this.$tt('tip_code_no_belong_track', { code: code }));
				}
				if (boxItem.finish == true) {
					this.$refs.error_audio.play();
					return this.$message.error(this.$tt('tip_code_has_add_finish', { code: code }));
				}
				this.$set(boxItem, 'scanNumber', boxItem.actualNum);
				this.$set(boxItem, 'finish', true);
				this.$set(
					track,
					'finish',
					track.waitPackSkuVOList.every((it) => it.finish == true)
				);
				if (track.finish == true && this.autoPushOver) {
					this.checkPackPush({ track: track, finishBeforeCall, finishCall, tipShow });
				}
			} else {
				const skuScan = (skus, scanSn) => {
					if (_.isEmpty(skus)) {
						this.$refs.error_audio.play();
						return this.$message.error(this.$tt('tip_skuBarcode_sku_no_belong_track', { skuBarcode: code }));
					}
					if (skus.every((it) => it.finish == true)) {
						this.$refs.error_audio.play();
						return this.$message.error(this.$tt('tip_skuBarcode_has_add_finish', { skuBarcode: code }));
					}
					let skuItem = _.find(skus, (it) => it.finish != true);
					const checkItemCount = Number(skuItem.actualNum);
					const will_set_number = (skuItem.scanNumber ? Number(skuItem.scanNumber) : 0) + 1;
					if (checkItemCount < will_set_number) {
						this.$refs.error_audio.play();
						return this.$message.error(this.$tt('tip_skuBarcode_count_has_over', { skuBarcode: skuItem.skuOnlyCode, count: checkItemCount }));
					}
					this.$set(skuItem, 'scanNumber', will_set_number);
					if (scanSn) {
						if (!skuItem.skuOutboundDetailList) {
							this.$set(skuItem, 'skuOutboundDetailList', []);
						}
						skuItem.skuOutboundDetailList.push({
							bizType: track.bizType,
							stockUsage: scanSn.stockUsage,
							qty: 1,
							snCode: scanSn.snCode,
						});
					}

					if (checkItemCount == will_set_number) {
						this.$set(skuItem, 'finish', true);
						track.waitPackSkuVOList.sort((a, b) => {
							return (a.finish ? 1 : 0) - (b.finish ? 1 : 0);
						});
						this.$set(
							track,
							'finish',
							track.waitPackSkuVOList.every((it) => it.finish == true)
						);
						if (track.finish == true && this.autoPushOver) {
							this.checkPackPush({ track: track, finishBeforeCall, finishCall, tipShow });
						}
					}
				};
				let skus = [];
				if (snSku) {
					skus = track.waitPackSkuVOList.filter((it) => it.skuId == snSku.skuId);
					skuScan(skus, snSku);
				} else {
					skus = track.waitPackSkuVOList.filter((it) => it.skuOnlyCode == code);
					if (_.isEmpty(skus)) {
						this.findSn({
							snCode: code,
							call: (snSkuOther) => {
								if (snSkuOther) {
									skuScan(
										track.waitPackSkuVOList.filter((it) => it.skuId == snSkuOther.skuId),
										snSkuOther
									);
								} else {
									skuScan(skus);
								}
							},
						});
					} else {
						skuScan(skus);
					}
				}
			}
		},

		checkSnIsScanPush(snCode) {
			if (this.trackItem && this.trackItem.waitPackSkuVOList.some((item) => item.skuOutboundDetailList && item.skuOutboundDetailList.some((snItem) => snItem.snCode == snCode))) {
				return true;
			} else if (this.tableData && this.tableData.some((item) => item.skuOutboundDetailList && item.skuOutboundDetailList.some((snItem) => snItem.snCode == snCode))) {
				return true;
			}
			return false;
		},
		//添加容器记录
		checkContainerPackPush({ track, finishBeforeCall, finishCall, tipShow }) {
			if (!track) {
				this.$refs.error_audio.play();
				return this.$message.error(this.$tt('label_get_track_info_fail'));
			}
			if (this.trackSwitchList.some((it) => it.trackNumber === track.trackNumber)) {
				this.$refs.error_audio.play();
				return this.$message.error(this.$tt('label_face_track_has_be_update'));
			}
			track.waitPackSkuVOList.forEach((it) => {
				this.$set(it, 'scanNumber', it.actualNum);
				this.$set(it, 'finish', true);
			});
			this.$set(track, 'finish', true);
			if (track.finish == true && this.autoPushOver) {
				this.checkPackPush({ track: track, finishBeforeCall, finishCall, tipShow });
			}
		},

		cancelTrackConfirm() {
			if (this.trackItem.waitPackSkuVOList.some((it) => it.scanNumber > 0)) {
				this.$confirm(this.$tt('tip_xxx_confirm_cancel_track_will_loss_all_sku', { code: this.trackItem.trackNumber }), this.$tt('label_tip'), {
					type: 'warning',
				})
					.then(() => {
						this.cancelTrack(this.trackItem);
						this.trackItem = null;
					})
					.catch(() => {});
			} else {
				this.cancelTrack(this.trackItem);
				this.trackItem = null;
			}
		},
		cancelHasAddTrack(row, i) {
			this.$confirm(this.$tt('tip_xxx_confirm_cancel_track_will_loss_all_sku', { code: row.trackNumber }), this.$tt('label_tip'), {
				type: 'warning',
			})
				.then(() => {
					const track = _.find(this.trackList, (it) => it.trackNumber == row.trackNumber);
					if (track) {
						this.cancelTrack(track);
					}
					this.tableData.splice(i, row.rowspan);
				})
				.catch(() => {});
		},

		cancelTrack(item) {
			// if (!item) item = this.trackItem
			this.$set(item, 'push_over', false);
			this.$set(item, 'finish', false);
			item.waitPackSkuVOList.forEach((it) => {
				this.$set(it, 'finish', false);
				this.$set(it, 'scanNumber', 0);
				this.$set(it, 'skuOutboundDetailList', []);
			});
		},

		checkSelfTempPrint(track) {
			if (!track.labelOssPath) {
				return true;
			} else {
				const printConfig = _.head(this.$refs.print_config_dialog.loadPrintConfig({ typeKey: track.platformCode }));
				if (printConfig && printConfig.tempPt) {
					return true;
				}
				return false;
			}
		},
		checkThreeTrackPrint(track) {
			return !!track.labelOssPath;
		},
		/**
		 * 推送面单记录
		 * @param {*} track 面单对象
		 * @param {*} pushfixobj 推送时固定的合并对象
		 * @param {*} call 回调
		 */
		checkPackPush({ track, finishBeforeCall, finishCall, tipShow }) {
			if (!track) track = this.trackItem;
			if (!track) return this.$message.error(this.$tt('tip_please_input_or_scan_track_code'));

			if (track.waitPackSkuVOList.reduce((r, v) => this.$math_add(r, v.scanNumber), 0) == 0) {
				this.$refs.error_audio.play();

				return this.$message.error(this.$tt('tip_sku_scan_count_no_empty'));
			}
			// if (!this.packTypeName) return this.$message.error(this.$tt('tip_pack_material_type_noEmpty'))
			// if (!this.packId) return this.$message.error(this.$tt('tip_pack_material_name_noEmpty'))

			if (this.tableData.some((it) => it.packageNo == track.trackNumber)) {
				this.$refs.error_audio.play();

				return this.$message.error(this.$tt('tip_trackNumber_check_pack_finish', { trackNumber: track.trackNumber }));
			}
			const willPushList = track.waitPackSkuVOList.map((skuItem, i) => {
				return {
					rowspan: i == 0 ? track.waitPackSkuVOList.length : 0,
					userId: this.$loginUser.userId,
					userName: this.$loginUser.userName,

					trackOwner: track.trackOwner,
					bizType: track.bizType,
					deviationRate: track.deviationRate,
					oldWaybillFlag: track.oldWaybillFlag,
					trackNumber: track.trackNumber,
					skuKindLength: track.skuKindLength,
					skuSum: track.skuSum,
					packageNo: track.trackNumber,
					outOrderNo: track.outOrderNo,
					outboundOrderNo: track.outOrderNo,
					labelOssPath: track.labelOssPath,
					isShortPick: !!track.isShortPick,
					// orderNO: track.outOrderNo,
					channelId: track.channelId,
					channelName: track.channelName,
					channelCode: track.channelCode,

					customerId: track.customerId,
					customerCode: track.customerCode,
					customerName: track.customerName,
					platformCode: track.platformCode,
					ecPlatformName: track.platformCode,
					packageBoxNo: skuItem.boxNo,
					number: skuItem.planNum,
					actualNum: skuItem.actualNum || '—',
					scanNumber: skuItem.scanNumber,
					skuId: skuItem.skuId,
					skuBarcode: skuItem.skuBarcode,
					skuOnlyCode: skuItem.skuOnlyCode,
					skuName: skuItem.skuNameCn,
					skuNameEn: skuItem.skuNameEn,
					customNumber: skuItem.customNumber,
					packageType: this.packTypeName,
					packageName: this.packName,
					materialStockId: this.packId,
					materialCode: this.packCode,
					skuWeight: this.$math_mul(skuItem.skuWeight, skuItem.scanNumber),
					skuVolume: this.$math_mul(skuItem.skuVolume, skuItem.scanNumber),
					skuOutboundDetailList: skuItem.skuOutboundDetailList,

					packUnit: 'PIECE',
					packCount: 1,
				};
			});

			const done = (_track, _willPushList) => {
				this.tableData.push(..._willPushList);

				// if (call) call(_track, _willPushList)
				this.$set(_track, 'push_over', true);
				if (tipShow != false) {
					this.$message.success(this.$tt('tip_trackNumber_has_add_finish', { trackNumber: _track.trackNumber }));
				}
				// this.searchCode = null
				// this.trackItem = null
				this.sortTrackList();

				if (finishCall) {
					finishCall(_track, _willPushList);
				} else {
					this.trackItem = null;
					if (this.trackList.length > 0) {
						const firstTrack = this.trackList[0];
						if (firstTrack && !firstTrack.finish) {
							this.trackItem = firstTrack;
						}
					}
					//自动选择下一个面单
					// setTimeout(() => {
					//   this.$nextTick(() => {
					//     if (this.trackList.length > 0) {
					//       const firstTrack = this.trackList[0]
					//       if (firstTrack && !firstTrack.finish) {
					//         this.trackItem = firstTrack
					//       }
					//     }

					//   })
					// }, 200)
				}
			};
			if (finishBeforeCall) {
				finishBeforeCall(track, willPushList, done);
			} else {
				done(track, willPushList);
			}
		},
		clearSkuCode() {
			this.searchCode = null;
		},
		clearTrackItem() {
			this.trackItem = null;
		},
		selectTrack(row) {
			this.trackItem = row;
		},
		autoPrintAction(tracks) {
			const switchFace = tracks.some((t) => t.switchFace);
			if (switchFace) {
				this.$refs.print_outbound_track.printDefaultOption({
					list: tracks,
					url: '/wms-api/outbound/OutboundOverseasOrderRpc/printExceptionWaybill.json',
					handler: (data, list) => {
						data.printTrackNumberList = list.map((it) => ({
							trackNumber: it.trackNumber,
							platformCode: it.platformCode,
							printNum: it.printNum,
						}));
						return data;
					},
					templateRequire: true,
				});
				return;
			}
			const selfTemps = tracks.filter((track) => this.checkSelfTempPrint(track));
			const threeTemps = tracks.filter((track) => this.checkThreeTrackPrint(track));

			if (!_.isEmpty(selfTemps)) {
				let track = _.head(selfTemps);
				this.$refs.print_outbound_track.printDefaultOption({
					list: selfTemps,
					extraBusinessType: this.checkThreeTrackPrint(track) ? track.platformCode : null,
					url: '/wms-api/outbound/OutboundOverseasOrderRpc/printWaybillByTrackNumber.json',
					handler: (data, list) => {
						data.printTrackNumberList = list.map((it) => ({
							trackNumber: it.trackNumber,
							platformCode: it.platformCode,
							printNum: it.printNum,
						}));
						return data;
					},
					templateRequire: true,
				});
			}
			if (!_.isEmpty(threeTemps)) {
				this.$refs.print_outbound_track.printDefaultOption({
					list: threeTemps,
					extraBusinessType: _.head(threeTemps).platformCode,
					url: '/wms-api/outbound/OutboundBoxPackageRpc/printPdfList.json',
					handler: (data, list) => ({
						paramList: list.map((it) => ({
							clientId: data.clientName,
							printerName: data.printerName,
							printCount: data.printNumSum,
							trackNumber: it.trackNumber,
							fileName: it.trackNumber,
							fileType: this.$reg.FileExt(it.labelOssPath), //data.fileType,
							labelOssPath: it.labelOssPath,
						})),
					}),
					templateRequire: false,
				});
			}
		},
		//确认打包前处理自动测量问题
		packFinishBeforeCall(track, willPushList, done) {
			//盘点sku -1 不自动测量

			this.autoMeasureForSkuNet({
				items: willPushList,
				success: (res) => {
					willPushList.forEach((it) => {
						it.plan = {
							packageWeight: res.weight,
							length: res.length,
							width: res.width,
							height: res.height,
						};
						if (this.autoMeasure) {
							this.$set(it, 'packageWeight', res.weight);
							this.$set(it, 'length', res.length);
							this.$set(it, 'width', res.width);
							this.$set(it, 'height', res.height);
						}
					});
					if (!Number.isNaN(Number(this.autoWeightValue)) && Number(this.autoWeightValue) > 0) {
						this.checkSwitchFaceTrack({
							newWeight: this.autoWeightValue,
							switchFaceTrackList: willPushList,
							success: (list, switchFace) => {
								willPushList.forEach((it) => {
									this.$set(it, 'packageWeight', this.autoWeightValue);
								});
								if (switchFace) {
									if (this.trackItem == track) {
										this.trackItem = null;
									}
									this.trackSwitchList.push(willPushList[0]);
								} else {
									done(track, willPushList);
								}
								if (this.autoPrint) {
									this.autoPrintAction([willPushList[0]]);
								}
							},
						});
					} else {
						if (this.autoPrint) {
							this.autoPrintAction([willPushList[0]]);
						}
						done(track, willPushList);
					}
				},
				fail: () => {
					this.$message.error(this.$t('label_face_track_weight_compute_fail'));
				},
			});
		},
		packFinishCall(tracks) {
			// track,willPushList
			// if (this.autoPrint) {
			//   this.autoPrintAction(tracks)
			// }
		},
		//扫描检查功能
		checkShowNext(track, searchType, snSku) {
			const olaHasTrack = !!this.trackItem;
			if (!track) {
				if (_.isEmpty(this.trackList)) {
					return;
				} else {
					this.getFirstTrack(this.trackList, this.searchCode, (otherTrack, snOtherSku) => {
						if (otherTrack) {
							this.checkShowNext(otherTrack, searchType, snOtherSku);
						}
					});
					return;
				}
			}
			const config = this.searchTypeList[searchType];
			if (track) {
				this.trackItem = track;
				const params = {
					code: this.searchCode,
					track: this.trackItem,
					snSku,
					finishBeforeCall: this.packFinishBeforeCall,
					finishCall: (track, willPushList) => {
						this.packFinishCall([willPushList[0]]);
					},
				};
				if (config.onlyOneTrack) {
					if (this.packageExamine) {
						if (olaHasTrack) {
							this.checkSkuPackPush(params);
						}
					} else {
						this.checkContainerPackPush(params);
					}
				} else {
					this.checkSkuPackPush(params);
				}
			}
		},
		pushCurrentTrackDown() {
			this.checkPackPush({
				track: this.trackItem,
				finishBeforeCall: this.packFinishBeforeCall,
				finishCall: (track, willPushList) => {
					this.packFinishCall([willPushList[0]]);
				},
			});
		},
		getFirstTrack(list, code, call) {
			const config = this.searchTypeList[this.searchType];
			const track = _.find(list, (v) => {
				if (v.finish == true) return false;
				if (v.interceptFlag == 'Y') return false;
				if (this.trackSwitchList.some((it) => it.trackNumber === v.trackNumber)) {
					return false;
				}

				if (config.onlyOneTrack) {
					return true;
				} else if (config.searchKey) {
					return v.waitPackSkuVOList.some((it) => it[config.searchKey] == code);
				} else {
					false;
				}
			});

			if (track == null && this.searchType == 'SKU') {
				this.findSn({
					snCode: code,
					call: (snSku) => {
						if (snSku) {
							const otherTrack = _.find(list, (v) => {
								if (v.finish == true) return false;
								if (this.trackSwitchList.some((it) => it.trackNumber === v.trackNumber)) {
									return false;
								}
								return v.waitPackSkuVOList.some((it) => it.skuId == snSku.skuId);
							});
							call(otherTrack, snSku);
						} else {
							call(track);
						}
					},
				});
			} else {
				call(track);
			}
		},
		findSn({ snCode, call }) {
			if (this.checkSnIsScanPush(snCode)) {
				this.$refs.error_audio.play();
				this.$message.error(this.$tt('tip_sn_code_has_push', { code: snCode }));
				return;
			}
			this.$ajax({
				url: '/wms-api/stock/StockQueryRpc/sn_detail.json',
				method: 'post',
				loading: '查找SN',
				data: {
					snCode: snCode,
				},
				fail: () => {
					if (call) call();
					// this.$refs.error_audio.play()
				},
				success: (res) => {
					if (res && res.data && res.data.skuId) {
						res.data.snCode = snCode;
						if (call) call(res.data);
					} else {
						if (call) call();
					}
				},
			});
		},
		getBatchTracks(list, code) {
			const _out = _.filter(list, (v) => {
				if (v.finish == true) return false;
				if (v.skuSum != 1) return false;
				if (this.searchType == 'SKU') {
					return v.waitPackSkuVOList.some((it) => it.skuOnlyCode == code);
				} else if (['CONTAINER', 'FACE'].includes(this.searchType)) {
					return true;
				} else if (this.searchType == 'BOX') {
					return v.waitPackSkuVOList.some((it) => it.boxNo == code);
				}
			});
			return _.take(_out, 999);
		},
		refreshTrackNet() {
			this.$refs.formSearch.validate((valid) => {
				if (valid) {
					this.getSkuLinkTrackNet(this.searchCode, (list) => {
						this.checkShowNext(null, this.searchType);
					});
				} else {
					return false;
				}
			});
		},
		//扫描sku
		scanSkuCode() {
			this.$refs.formSearch.validate((valid) => {
				if (valid) {
					// if (this.trackItem == null) {
					//   this.getSkuLinkTrackNet(this.searchCode, (list) => {
					//     this.checkShowNext(null, this.searchType)
					//   })
					// }
					// else
					if (this.trackItem && !this.trackItem.push_over) {
						this.checkShowNext(this.trackItem, this.searchType);
					} else if (_.isEmpty(this.trackList)) {
						this.getSkuLinkTrackNet(this.searchCode, (list) => {
							this.checkShowNext(null, this.searchType);
						});
					} else {
						this.getFirstTrack(this.trackList, this.searchCode, (firstTrack, snSku) => {
							if (firstTrack == null || firstTrack.finish == true) {
								// return this.$message.error(this.$tt('tip_sku_trackNumber_has_add_finish', { sku: this.searchCode }))
								this.getSkuLinkTrackNet(this.searchCode, (list) => {
									this.checkShowNext(null, this.searchType, snSku);
								});
							} else if (!firstTrack.isShortPick && firstTrack.skuSum == 1) {
								this.checkShowNext(firstTrack, this.searchType, snSku);
							} else {
								this.checkShowNext(firstTrack, this.searchType, snSku);
							}
						});
					}
				} else {
					return false;
				}
			});
		},

		//查找面单
		getSkuLinkTrackNet(code, call) {
			const config = this.searchTypeList[this.searchType];
			const data = {};
			data[config.netKey] = code;
			if (!_.isEmpty(this.orderStructures)) {
				data.orderStructures = this.orderStructures;
			}
			this.$ajax({
				url: '/wms-api/outbound/OutboundBoxPackageRpc/matchWaitPackage.json',
				method: 'post',
				type: 'json',
				loading: true,
				data,
				failure: () => {
					this.$refs.error_audio.play();
				},
				success: (res) => {
					if (res && res.data && res.data.rows) {
						if (_.isEmpty(res.data.rows)) {
							this.$message.error(this.$tt('label_code_no_associated_face_track', { code }));
							return;
						} else {
							this.clearTrackItem();
							this.trackList = [];
							this.linkSearchCode = code;
							res.data.rows.forEach((it) => (it.platformCode = it.ecPlatformName));
							this.trackList = res.data.rows;
							this.refrashSkuLinkTrack();
							if (call) call(this.trackList);
						}
					}
				},
			});
		},

		refrashSkuLinkTrack() {
			this.trackList.forEach((it) => {
				this.$set(it, 'skuKindLength', it.waitPackSkuVOList.length);
				this.$set(
					it,
					'skuSum',
					_.reduce(it.waitPackSkuVOList, (sum, v) => sum + v.actualNum, 0)
				);
				it.waitPackSkuVOList.forEach((o) => {
					let scanNumber = 0;
					let item = _.find(this.tableData, (l) => l.packageNo == it.trackNumber && l.skuOnlyCode == o.skuOnlyCode);
					if (item) {
						scanNumber = item.scanNumber;
					}
					this.$set(o, 'finish', !!item);
					this.$set(o, 'scanNumber', scanNumber);
				});
				this.$set(
					it,
					'finish',
					it.waitPackSkuVOList.every((o) => o.finish)
				);
				this.$set(it, 'push_over', it.finish);
			});
			this.sortTrackList();
		},
		sortTrackList() {
			this.trackList.sort((a, b) => {
				if (a.push_over != b.push_over) {
					return (a.push_over ? 1 : 0) - (b.push_over ? 1 : 0);
				} else if (a.waitPackSkuVOList.length != b.waitPackSkuVOList.length) {
					return a.waitPackSkuVOList.length - b.waitPackSkuVOList.length;
				} else {
					return a.skuSum - b.skuSum;
				}
			});
		},
		scanTrackNumber(keyTrack) {
			if (keyTrack.oldWaybillFlag == 'Y') {
				this.$message.error(this.$t('label_face_track_has_be_update'));
				return;
			}
			if (this.trackItem) {
				if (this.trackItem.finish != true) {
					return this.$message.error(this.$tt('tip_trackNumber_no_check_pack_finish', { trackNumber: this.trackItem.trackNumber }));
				} else if (this.trackItem.push_over != true) {
					return this.$message.error(this.$tt('tip_trackNumber_no_check_pack_finish', { trackNumber: this.trackItem.trackNumber }));
				}
			}
			if (!keyTrack) return this.$message.error(this.$tt('tip_please_input_or_scan_track_code'));
			// if (!this.linkSearchCode) return this.$message.error(this.$tt('tip_scan_sku_code_first'))
			const linkTrack = _.find(this.trackList, (it) => it.trackNumber == keyTrack);
			if (!linkTrack) {
				return this.$message.error(this.$tt('label_get_track_info_fail'));
			} else if (linkTrack.interceptFlag == 'Y') {
				return this.$message.error(this.$tt('label_order_has_intercept'));
			}
			this.linkTrackNumber = keyTrack;
			this.trackItem = linkTrack;
		},
		reviewConfirm() {
			if (_.isEmpty(this.tableData)) {
				return this.$message.error(this.$tt('tip_check_pack_first'));
			}
			if (
				this.tableData.some((it) => _.isEmpty(it.packageWeight)) ||
				this.tableData.some((it) => _.isEmpty(it.length)) ||
				this.tableData.some((it) => _.isEmpty(it.width)) ||
				this.tableData.some((it) => _.isEmpty(it.height))
			) {
				return this.$message.error(this.$tt('tip_measure_first'));
			}
			this.$confirm(this.$tt('tip_xxx_confirm_action_type', { type: this.$tt('title_standard_check_pack') }), this.$tt('label_tip'), {
				type: 'warning',
			})
				.then(() => {
					this.submitQueue(_.chunk(this.tableData, 50), 0);
				})
				.catch(() => {});
		},
		submitData({ list, success, failure }) {
			let savePackageList = list;
			//判断重货
			savePackageList.forEach((it) => {
				it.heavyCargoFlag = it.packageWeight > 25 ? 'Y' : 'N';
				if (!it.skuOutboundDetailList) {
					it.skuOutboundDetailList = [];
				}
				const no_common_qty = _.reduce(it.skuOutboundDetailList, (sum, scanItem) => sum + scanItem.qty, 0);
				const last_qty = it.scanNumber - no_common_qty;
				if (last_qty > 0) {
					it.skuOutboundDetailList.push({
						bizType: it.bizType,
						stockUsage: 'COMMON_SALE',
						qty: last_qty,
					});
				}
			});

			this.$ajax({
				url: '/wms-api/outbound/OutboundBoxPackageRpc/review.json',
				method: 'post',
				type: 'json',
				data: {
					savePackageList,
				},
				success: (res) => {
					success(list);
					this.$emitPage('outbound>check_pack_record', 'reload');
					this.$message.success(this.$tt('tip_submit_success'));
					this.clearSkuCode();
					this.trackList = [];
					this.clearTrackItem();
					this.tableData = [];
				},
				failure: () => {
					failure();
				},
				complete: () => {},
			});
		},
		submitQueue(chunklist, i, loading) {
			// let sliceLen = list.length
			// if (list.length > 50) {
			//   sliceLen = 50
			// }
			if (!loading) {
				loading = this.$loading({
					lock: true,
					text: this.$t('tip_submiting'),
				});
			}
			//_.chunk(list, 50)
			const willSubmitList = chunklist[i];
			this.submitData({
				list: willSubmitList,
				success: () => {
					willSubmitList.forEach((it) => {
						this.deleteRow(it);
					});
					i = i + 1;
					if (i == chunklist.length) {
						this.$emitPage('outbound>check_pack_record', 'reload');
						// this.$message.success(this.$tt('tip_submit_success'))
						this.clearSkuCode();
						this.trackList = [];
						this.clearTrackItem();
						this.tableData = [];
						if (loading) {
							loading.close();
						}
					} else {
						this.submitQueue(chunklist, i, loading);
					}
				},
				failure: () => {
					if (loading) {
						loading.close();
					}
				},
			});
		},
		deleteRow(row) {
			const i = this.tableData.indexOf(row);
			if (i >= 0) this.tableData.splice(i, 1);
			this.trackList = this.trackList.filter((it) => it.trackNumber != row.trackNumber);
		},
		modifyRecord(row) {
			const dataList = this.tableData.filter((it) => it.packageNo == row.packageNo);
			this.$msgbox_table(
				{
					note: this.$tt('label_modify_count'),
					tableProp: {
						data: dataList,
						model: [
							{ key: 'packageNo', label: 'label_track_or_package_code', 'show-overflow-tooltip': true },
							{ key: 'skuOnlyCode', label: 'label_sku_only_code', 'show-overflow-tooltip': true },
							{
								key: 'number',
								label: 'label_sku_count',
								'min-width': 120,
								'show-overflow-tooltip': true,
							},
							{
								key: 'scanNumber',
								label: 'label_scan_count',
								'min-width': 140,
								component: ({ row }) => {
									return {
										type: 'input-number',
										class: 'w_fill',
										attrs: { min: 0, max: row.number, 'step-strictly': true },
										// on: { change: (v) => this.skuNumberChange(row) }
									};
								},
							},
						],
					},
				},
				{
					type: 'warning',
					customClass: 'dialog_small',
					showCancelButton: true,
					confirmButtonText: this.$tt('label_confirm'),
					cancelButtonText: this.$tt('label_cancel'),
					beforeClose: (action, instance, done) => {
						dataList.forEach((it) => this.$set(it, 'error', {}));
						if (action == 'confirm') {
							let checkOk = true;
							dataList.forEach((it) => {
								const v = it.scanNumber;
								if (_.isEmpty(v)) {
									it.error.scanNumber = this.$tt('tip_can_no_empty');
									checkOk = false;
								} else if (!this.$reg.PureNumber(v) || Number.isNaN(Number(v))) {
									it.error.scanNumber = this.$tt('tip_only_positive_pure_decimal');
									checkOk = false;
								} else if (Number(v) > Number(it.number)) {
									it.error.scanNumber = this.$tt('tip_no_more_plan_count');
									checkOk = false;
								}
							});
							if (dataList.reduce((r, v) => this.$math_add(r, v.scanNumber), 0) == 0) {
								this.$message.error('打包数量不能都为空');
								checkOk = false;
							}
							if (checkOk) {
								dataList.forEach((it) => {
									const item = _.find(this.tableData, (org) => org.packageNo == it.packageNo && org.skuOnlyCode == it.skuOnlyCode);
									if (item) {
										item.scanNumber = it.scanNumber;
									}
								});
								done();
							}
						} else {
							done();
						}
					},
				}
			)
				.then(() => {})
				.catch(() => {});
		},
	},
};
</script>
<style></style>
